package LeetCode;

import java.util.LinkedList;
import java.util.Stack;

public class Solution2 {
    public static void main(String[] args) {
        String[] strings = {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
        System.out.println(evalRPN(strings));
    }

    public static int evalRPN(String[] tokens) {
        LinkedList<Integer> stack = new LinkedList<>();
        for (int i = 0; i < tokens.length; i++) {
            int a = 0;
            int b = 0;
            switch (tokens[i]) {
                case "+":
                    b = stack.pop();
                    a = stack.pop();
                    stack.push(a + b);
                    break;
                case "-":
                    b = stack.pop();
                    a = stack.pop();
                    stack.push(a - b);
                    break;
                case "*":
                    b = stack.pop();
                    a = stack.pop();
                    stack.push(a * b);
                    break;
                case "/":
                    b = stack.pop();
                    a = stack.pop();
                    stack.push(a / b);
                    break;
                default:
                    stack.push(Integer.parseInt(tokens[i]));
                    break;
            }
        }

        return stack.pop();
    }


    public static void main1(String[] args) {
        String[] strings = {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
        System.out.println(inversePolishSolving(strings));
    }

    public static double inversePolishSolving(String[] strings) {
        if (strings.length == 0) {
            return -1;
        }
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < strings.length; i++) {
            if (strings[i].equals("+") || strings[i].equals("-") || strings[i].equals("*") || strings[i].equals("/")) {
                String num1 = stack.pop();
                String num2 = stack.pop();
                double n1 = Double.parseDouble(num1);
                double n2 = Double.parseDouble(num2);
                if (strings[i].equals("+")) {
                    double n = n1 + n2;
                    stack.push(String.valueOf(n));
                    continue;
                }
                if (strings[i].equals("-")) {
                    double n = n2 - n1;
                    stack.push(String.valueOf(n));
                    continue;
                }
                if (strings[i].equals("*")) {
                    double n = n2 * n1;
                    stack.push(String.valueOf(n));
                    continue;
                }
                if (strings[i].equals("/")) {
                    double n = n2 / n1;
                    stack.push(String.valueOf(n));
                }

            }else {
                stack.push(strings[i]);
            }
        }
        return Double.parseDouble(stack.peek());
    }

}
